# Copyright 2020 Tecnativa - Ernesto Tejeda
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

from odoo import _, api, fields, models
from odoo.exceptions import ValidationError


class RmaReWorkWizard(models.TransientModel):
    _name = "rma.rework.wizard"
    _description = "RMA Rework Wizard"

    rma_count = fields.Integer()
    type = fields.Selection(
        selection=[("rework", "Rework/Reprocessing"), ("tofgi", "Transfer Warehouse")],
        required=True,
    )
    product_id = fields.Many2one(
        comodel_name="product.product",
        string="Product",
    )
    product_uom_qty = fields.Float(
        string="Product qty",
        digits="Product Unit of Measure",
    )
    to_done_qty = fields.Float(
        string="Pending Quantity",
        digits="Product Unit of Measure",
    )
    product_uom = fields.Many2one(comodel_name="uom.uom", string="Unit of measure")
    scheduled_date = fields.Datetime(required=True, default=fields.Datetime.now)
    warehouse_id = fields.Many2one(
        comodel_name="stock.warehouse",
        string="Warehouse",
        required=True,
    )
    uom_category_id = fields.Many2one(related="product_id.uom_id.category_id")
    remake_flag = fields.Boolean("Reprocessing")
    rework_flag = fields.Boolean("Rework")
    is_manufacture = fields.Boolean("is_manufacture")
    production_ids = fields.Many2many('mrp.production')
    production_id = fields.Many2one('mrp.production', "Source WorkOrder", domain="[('id', 'in', production_ids)]")
    rma_ids = fields.Many2many('rma')
    dest_location_id = fields.Many2one(
        comodel_name="stock.location",
        string="Target Warehouse"
    )

    @api.constrains("to_done_qty")
    def _check_to_done_qty(self):
        self.ensure_one()
        rma_ids = self.env.context.get("active_ids")
        if len(rma_ids) == 1 and self.to_done_qty <= 0:
            raise ValidationError(_("Quantity must be greater than 0."))

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        rma_ids = self.env.context.get("active_ids")
        rma = self.env["rma"].browse(rma_ids)
        warehouse = self.env["stock.warehouse"].search([("company_id", "=", rma[0].company_id.id)], limit=1)
        warehouse_id = warehouse.id
        delivery_type = self.env.context.get("rma_action_type")
        product_id = rma.product_id.id

        # product_id = False
        # if len(rma) == 1 and delivery_type == "return":
        #     product_id = rma.product_id.id
        # if len(rma) == 1 and delivery_type == "replace":
        #     product_id = rma.product_id.id

        product_uom_qty = 0.0
        to_done_qty = 0
        if len(rma) == 1 and rma.remaining_qty > 0.0:
            product_uom_qty = rma.remaining_qty
            if delivery_type == 'rework':
                to_done_qty = rma.scrap_qty
            if delivery_type == 'tofgi':
                to_done_qty = rma.good_qty
        res.update(
            rma_ids=rma_ids,
            rma_count=len(rma),
            warehouse_id=warehouse_id,
            type=delivery_type,
            product_id=product_id,
            product_uom_qty=product_uom_qty,
            to_done_qty=to_done_qty,
            dest_location_id=warehouse.lot_stock_id.id
        )
        return res

    @api.onchange("product_id")
    def _onchange_product_id(self):
        if self.product_id:
            if not self.product_uom or self.product_id.uom_id.id != self.product_uom.id:
                self.product_uom = self.product_id.uom_id
                self.is_manufacture = self.product_id.is_manufacture
                lines = self.env['mrp.production'].search(
                    [('product_id', '=', self.product_id.id), ('state', '=', 'done')])
                self.production_ids = lines.ids
        else:
            self.is_manufacture = True

    def action_done(self):
        self.ensure_one()
        rma_ids = self.env.context.get("active_ids")
        rma = self.env["rma"].browse(rma_ids)
        if self.type == "rework":
            if self.remake_flag == True and self.rework_flag == True:
                raise ValidationError(_("Please choose between rework or reprocessing."))
            if self.remake_flag == True or self.rework_flag == True:
                if not self.production_id:
                    raise ValidationError(_("Please select the source work order."))
            # create_rework(self, scheduled_date, warehouse, product, qty, uom, rework, remark, origin):
            rma.create_rework(
                self.scheduled_date,
                self.warehouse_id,
                self.product_id,
                self.to_done_qty,
                self.product_uom,
                self.rework_flag, self.remake_flag, self.production_id
            )
            # 增加重工重制标志
        elif self.type == "tofgi":
            # def create_tofgi(self, dest_location_id, qty):
            rma.create_tofgi(
                self.dest_location_id,
                self.to_done_qty
            )
